/*
 * @Descripttion:
 * @Author: liuyu
 * @Date: 2023-12-04 15:44:23
 * @LastEditors: liuyu
 * @LastEditTime: 2023-12-04 15:44:23
 * @FilePath: /app/controller/menu.js
 */
'use strict';

const Controller = require('egg').Controller;
class MenuController extends Controller {
  async show() {
    const { ctx: { service, helper, params } } = this;
    const res = await service.menu.show({ menu_id: params.id });
    helper.render(200, res);
  }
  async list() {
    const { ctx } = this;
    const menus = await ctx.service.menu.index();
    // const res = await ctx.service.menu.index();
    const allMenu = ctx.helper.toTree(menus, 'parent_id', 'menu_id');
    ctx.helper.render(200, {
      data: allMenu,
    });
  }
  // async list() {
  //   const { ctx } = this;
  //   const role_id = ctx.query.role_id || ctx.locals.auth.role_id;
  //   console.log(role_id, 'role_id');
  //   const role_menu_ids = await ctx.service.role.menuids(role_id);
  //   let menus = [];
  //   if (ctx.locals.auth.role_id === 0) {
  //     menus = await ctx.service.menu.index();
  //   } else {
  //     if (role_menu_ids.length <= 0) {
  //       menus = [];
  //     } else {
  //       menus = await ctx.service.menu.index({
  //         menu_id: role_menu_ids,
  //       });
  //     }
  //   }
  //   // const res = await ctx.service.menu.index();
  //   const allMenu = ctx.helper.toTree(menus, 'parent_id', 'menu_id');
  //   ctx.helper.render(200, {
  //     data: allMenu,
  //   });
  // }
  async create() {
    const { ctx: { service, helper, request } } = this;
    const body = request.body;
    // const userInfo = await service.userAdmin.show({ id: ctx.locals.auth.userAdminBid });
    const showRes = await service.menu.show({ menu_name: body.menu_name, parent_id: body.parent_id });
    if (showRes) {
      helper.render(422, {}, '菜单名称已存在');
      return;
    }
    try {
      await service.menu.create(body);
      helper.render(200, {}, '添加成功');
    } catch (e) {
      helper.render(422, e, '添加失败');
    }
  }
  async update() {
    const { ctx: { service, helper, params, request } } = this;
    const body = request.body;
    const showRes = await service.menu.show({ menu_name: body.menu_name, parent_id: body.parent_id });
    if (showRes && `${showRes.id}` !== `${params.id}`) {
      helper.render(422, {}, '菜单名称已存在');
      return;
    }
    const options = {
      where: { menu_id: params.id },
    };
    try {
      await service.menu.update(body, options);
      helper.render(200, {}, '更新成功');
    } catch (e) {
      helper.render(422, e, '更新失败');
    }
  }
  async delete() {
    const { ctx: { service, helper, params } } = this;
    try {
      await service.menu.delete(params.id);
      helper.render(200, {}, '删除成功');
    } catch (e) {
      helper.render(422, e, '删除失败');
    }
  }
}

module.exports = MenuController;
